package Servlet;

import DAO.DAOFactory;
import DAO.PackageDAO;
import javabean.Customer;
import javabean.customerPackage;
import javabean.Package;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/ChangePackage")
public class ChangePackageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType( "text/html; charset=UTF-8");
        PackageDAO packageDAO = (PackageDAO) DAOFactory.getPackageDAOInstance();
        HttpSession session = req.getSession();
        Customer customer = (Customer) session.getAttribute("loginCustomer"); // login user
        String selectedPackageId = req.getParameter("selectedPackage");
        System.out.println("selectedPackage" + selectedPackageId);
        System.out.println("customer" + customer.getCustomerID());
        if (selectedPackageId != null && !selectedPackageId.isEmpty()) {
            try {
                int packageID = Integer.parseInt(selectedPackageId);
                Package selectedPackage = packageDAO.getPackageByID(packageID);

                if(packageDAO.subscribePackage(selectedPackage, customer)){
                    customerPackage customerPackage = packageDAO.GetCustomerPackage(customer);//获取当前用户的套餐信息
                    session.setAttribute("curPackage", customerPackage);
                    req.getRequestDispatcher("MyPackage.jsp").forward(req, resp);
                }else{
                    PrintWriter out = resp.getWriter();
                    out.print("<script>alert('订购成功');window.location.href='Subpackage';</script>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                resp.sendRedirect("index.jsp");
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
